<template>
  <div class="bg-white">
    <div :id="eleId.replace('#', '')"></div>
    <div id="myflow_tools" class="ui-widget-content">
      <div id="myflow_tools_handle" style="text-align: center" class="ui-widget-header"
        >工具条
      </div>
      <div class="node" id="myflow_redraw"
        ><img src="../../../../../../../../../assets/images/flow/create.png" />&nbsp;&nbsp;新建</div
      >
      <div class="node" id="myflow_save" style="display: none"
        ><img src="../../../../../../../../../assets/images/flow/save.png" />&nbsp;&nbsp;保存</div
      >
      <div class="node" id="myflow_revoke"
        ><img src="../../../../../../../../../assets/images/flow/undo.png" />&nbsp;&nbsp;撤销</div
      >
      <!-- <div class="node" onclick="window.location.reload()"
        ><img src="../../../../../../../assets/images/flow/refresh.png" />&nbsp;&nbsp;刷新</div
      > -->
      <div class="node" id="myflow_del"
        ><img src="../../../../../../../../../assets/images/flow/del.png" />&nbsp;&nbsp;删除</div
      >
      <div>
        <hr />
      </div>
      <div class="node selectable selected" id="pointer"
        ><img src="../../../../../../../../../assets/images/flow/select.png" />&nbsp;&nbsp;选择
      </div>
      <div class="node selectable" id="path"
        ><img src="../../../../../../../../../assets/images/flow/path.png" />&nbsp;&nbsp;连线
      </div>
      <div class="node selectable" id="pathReturn"
        ><img src="../../../../../../../../../assets/images/flow/return.png" />&nbsp;&nbsp;返回
      </div>
      <div>
        <hr />
      </div>
      <div class="node state" id="task" type="task"
        ><img src="../../../../../../../../../assets/images/flow/task.png" />&nbsp;&nbsp;任务
      </div>
    </div>
    <!-- <div class="isPlay">
      <a-button type="primary" @click="PlayDesigner">回放</a-button>
    </div> -->
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, watchEffect, onMounted, nextTick, watch, computed } from 'vue';
  import type { PropType } from 'vue';
  import { ajaxGet, ajaxPost } from '/@/utils/utils';
  import { getAdminFlowGetFlowJson } from '/@/api/flowManage/flowManage';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useFlowStore } from '/@/store/modules/flow';
  import { ConsoleSqlOutlined } from '@ant-design/icons-vue';
  import { WorkflowLinkDb, WorkflowPredefineDb } from '/@/enums/flowManage';
  export default defineComponent({
    components: {},
    props: {
      typeCode: {
        type: String as PropType<string>,
        required: false,
      },
      eleId: {
        type: String as PropType<string>,
        required: false,
        default: '#myflow',
      },
    },
    emits: ['select'],
    setup(props, { emit }) {
      const flowData = ref({});
      let $flow;
      const useFlow = useFlowStore();
      const {} = useMessage();
      const curInternalName = ref('');
      const actionSelected = ref(false);
      const curAction = ref({});
      // watchEffect(() => {
      //   props.typeCode && fetch();
      // });
      // watch(
      //   () => props.typeCode,
      //   (newVal) => {
      //     if (newVal) fetch();
      //   },
      //   {
      //     immediate: true,
      //   },
      // );
      const currentFlowRecord = ref({});
      const fetch = async () => {
        await nextTick();
        getAdminFlowGetFlowJson({ typeCode: props.typeCode }).then((res) => {
          // console.log('res', res);
          let flowJson = res.flowJson;
          // eval这种方式转json不安全，eval会执行json串中的表达式，反斜杠会丢失，所以要先将\转为\\。
          flowJson = flowJson.replaceAll('\\\\', '\\\\');
          // 因为flowData书写不规范，键上面没有带引号，所以JSON.parse及$.parseJSON解析时都会报错
          if (flowJson == '') {
            flowJson = '{}';
          }
          flowData.value = eval('(' + flowJson + ')');
          const id = props.eleId; //'#myflowEdit';
          console.log('id', id);
          console.log(' $(`${id}`)', $(`${id}`));
          // $(`${id}`).myflow({
          //   editable: false,
          // });
          $(`${id}`).html('');
          $flow = $(`${id}`).myflow({
            allowStateMultiLine: false,
            editable: true,
            textEllipsis: true, // 如果节点的text过长，是否显示省略号
            textMaxLen: 18, // 与ellipsis联用，当ellipsis为true时生效
            // expireUnit: flowData.value.flowExpireUnit,
            licenseKey: res.licenseKey,
            // cloudUrl: flowData.value.cloudUrl,
            restore: flowData.value, //eval('(' + flowData.value + ')'),
            tools: {
              save: function (data) {
                // console.log("保存", data);
                // submitDesigner();
                // window.localStorage.setItem("data", data)
              },
              /*publish: function (data) {
                      console.log("发布", eval("(" + data + ")"));
                  },*/
              addPath: function (id, data) {
                console.log('添加路径', id, eval('(' + data + ')'));
              },
              addRect: function (id, data) {
                console.log('添加状态', id, eval('(' + data + ')'));
              },
              clickPath: function (id, data) {
                console.log('点击线', id, eval('(' + data + ')'));
                const newData = eval('(' + data + ')');
                const currentData = eval('(' + data + ')').props;

                // handleCurrentItem(id, currentData);

                // 取得其from节点，判断是否为条件分支
                // let myflow = $flow;
                // console.log('myflow', myflow);
                let path = getLink(id); //myflow.getPaths()[id];

                let lineModel: any = {
                  conditionType: currentData?.conditionType?.value,
                  desc: currentData?.desc?.value,
                  expireAction: currentData?.expireAction?.value,
                  expireHour: currentData?.expireHour?.value,
                  text: currentData?.text?.value,
                  title: currentData?.title?.value,
                  isFlagXorRadiate: false, //如果是false,只展示到期和超期
                  compare: '',
                  from: newData.from,
                  to: newData.to,
                };
                // console.log(path.from());
                let flag = path.from().getPropVal('ActionFlag');
                console.log('flag', flag);
                var isFlagXorRadiate = false;
                if (flag.length >= 7) {
                  if (flag.substr(6, 1) == '1') {
                    isFlagXorRadiate = true;
                  }
                }
                console.log('isFlagXorRadiate', isFlagXorRadiate);
                // if (isFlagXorRadiate) {
                //   OpenLinkPropertyWin(id);
                // } else {
                // OpenLinkPropertyNormalWin(id);
                // }
                OpenLinkPropertyWin(id);
                lineModel.isFlagXorRadiate = isFlagXorRadiate;
                if (lineModel.conditionType == WorkflowLinkDb.COND_TYPE_SCRIPT) {
                  lineModel.rawTitle = '脚本';
                } else {
                  if (
                    lineModel.conditionType == WorkflowLinkDb.COND_TYPE_ROLE ||
                    lineModel.conditionType == WorkflowLinkDb.COND_TYPE_DEPT ||
                    lineModel.conditionType == WorkflowLinkDb.COND_TYPE_DEPT_BELONG
                  ) {
                    // $.ajax({
                    //   type: 'post',
                    //   url: 'flow_designer_link_prop.jsp',
                    //   data: {
                    //     op: lineModel.conditionType,
                    //     codes: t,
                    //   },
                    //   dataType: 'html',
                    //   beforeSend: function (XMLHttpRequest) {},
                    //   success: function (data, status) {
                    //     lineModel.rawTitle = data;
                    //   },
                    //   complete: function (XMLHttpRequest, status) {},
                    //   error: function (XMLHttpRequest, textStatus) {
                    //     alert(XMLHttpRequest.responseText);
                    //   },
                    // });
                  } else {
                    lineModel.rawTitle = lineModel.title;
                  }
                }
                const t = lineModel.title;
                if (lineModel.conditionType == WorkflowLinkDb.COND_TYPE_FORM) {
                  if (t) {
                    if (t.indexOf('>=') != -1) lineModel.compare = '>=';
                    else if (t.indexOf('<=') != -1) lineModel.compare = '<=';
                    else if (t.indexOf('<>') != -1) lineModel.compare = '<>';
                    else if (t.indexOf('>') != -1) lineModel.compare = '>';
                    else if (t.indexOf('<') != -1) lineModel.compare = '<';
                    else if (t.indexOf('=') != -1) lineModel.compare = '=';
                    var ary = t.split(lineModel.compare);
                    lineModel.fields = ary[0];
                    lineModel.condValue = ary[1];
                  }
                } else if (
                  lineModel.conditionType == WorkflowLinkDb.COND_TYPE_DEPT ||
                  lineModel.conditionType == WorkflowLinkDb.COND_TYPE_DEPT_BELONG
                ) {
                  lineModel.depts = t ? t.split(',') : [];
                } else if (lineModel.conditionType == WorkflowLinkDb.COND_TYPE_ROLE) {
                  lineModel.depts = t;
                } else if (lineModel.conditionType == WorkflowLinkDb.COND_TYPE_SCRIPT) {
                  lineModel.deptNames = t;
                }

                lineModel.hiddenCondition = useFlow.flowEdit?.linkProps;
                let linkProps = useFlow.flowEdit?.linkProps; //window.parent.getProps();
                let xml = $.parseXML(linkProps);
                console.log({ linkProps, xml });
                let $xml = $(xml);
                console.log('linkProps-$xml', $xml);
                try {
                  let linkList: any = [];
                  $xml
                    .find('links')
                    .children()
                    .each(function (i) {
                      if (
                        $(this).find('from').text() == lineModel.from &&
                        $(this).find('to').text() == lineModel.to
                      ) {
                        let obj = {
                          from: $(this).find('from').text(),
                          to: $(this).find('to').text(),
                          firstBracket: $(this).find('firstBracket').text(),
                          fieldName: $(this).find('fieldName').text(),
                          mainColumn: $(this).find('name').text(),
                          compare: $(this).find('operator').text(),
                          value: $(this).find('value').text(),
                          twoBracket: $(this).find('twoBracket').text(),
                          logical: $(this).find('logical').text(),
                          fieldType: $(this).find('fieldType').text(),
                          columnName: '',
                          role: '',
                          userDept: '',
                        };
                        if (obj.mainColumn == WorkflowPredefineDb.COMB_COND_TYPE_FIELD) {
                          obj['columnName'] = obj.value;
                        }
                        if (obj.mainColumn == WorkflowPredefineDb.COMB_COND_TYPE_PRIV_ROLE) {
                          obj['role'] = obj.value;
                        }
                        if (obj.mainColumn == WorkflowPredefineDb.COMB_COND_TYPE_PRIV_DEPT) {
                          obj['userDept'] = obj.value;
                        }
                        for (let v in obj) {
                          console.log('obj[v]', obj[v]);
                          if (obj[v] == null || obj[v] == 'null') {
                            obj[v] = '';
                          }
                        }
                        console.log('obj', obj);
                        linkList.push(obj);
                      }
                    });
                  console.log('linkList-3', linkList);
                  if (linkList.length == 0) {
                    linkList.push({
                      from: lineModel.from,
                      to: lineModel.to,
                      firstBracket: '',
                      fieldName: '',
                      mainColumn: '',
                      compare: '',
                      value: '',
                      twoBracket: '',
                      logical: '',
                      fieldType: '',
                      columnName: '',
                      role: '',
                      userDept: '',
                    });
                  }
                  lineModel.linkList = linkList;
                } catch (err) {
                  console.log('links', err);
                }
                useFlow.setCurrentFlowData(lineModel);
                emit('select', 'path');
                console.log('select-path');
              },
              clickRect: function (id, data) {
                // console.log(data);
                console.log('点击状态', id, eval('(' + data + ')'));
                const currentData = eval('(' + data + ')').props;
                const inDegree = eval('(' + data + ')').inDegree;
                currentData.inDegree = inDegree;
                handleCurrentItem(id, currentData);
                // OpenModifyWin(eval("(" + data + ")"));
                if (curInternalName.value != id) {
                  OpenModifyWin(id);
                }
              },
              deletePath: function (id) {
                console.log('删除线', id);
              },
              deleteRect: function (id, data) {
                console.log('删除状态', id, eval('(' + data + ')'));
              },
              revoke: function (id) {
                console.log('撤销', id);
              },
            },
          });
          console.log(`${props.eleId}`, $flow, $(props.eleId));
        });
      };
      const getAction = (internalName) => {
        let myflow = $.myflow;
        return myflow.getStates()[internalName];
      };
      const OpenModifyWin = (internalName) => {
        actionSelected.value = true;
        curAction.value = getAction(internalName);
        console.log('curAction', curAction.value);
        console.log('curAction-id', curAction.value?.getId());

        curInternalName.value = internalName;
        useFlow.setFlowInfo({
          actionSelected: actionSelected.value,
          curAction: curAction.value,
          curInternalName: curInternalName.value,
        });
        $('#tabs').tabs('option', 'active', 1);
      };
      function switchKind(kind) {
        return;
      }

      //当前选中
      const handleCurrentItem = (id, currentData) => {
        currentFlowRecord.value = {
          title: currentData?.ActionTitle?.value,
          relateRoleToOrganization: currentData?.ActionProxyUserRealName?.value == '1',
          userName: currentData?.ActionJobCode?.value.replaceAll('comma', ','),
          relateToAction: 'default',
          relateDeptManager: false,
          userRealName: currentData?.ActionJobName?.value?.replaceAll('comma', ','),
          spanMode: '',
          rank: currentData?.ActionProxyJobName?.value,
          checkState: currentData?.ActionCheckState?.value,
          dept: currentData?.ActionDept?.value
            ? currentData?.ActionDept?.value.replaceAll('comma', ',').split(',')
            : [],
          fieldWriteText: '',
          fieldHideText: '',
          item1: currentData?.ActionItem1?.value == '' ? '0' : currentData?.ActionItem1?.value,
          trFlag: '',
          gjxz: '',
          ignoreType: '',
          kind: '0',
          // isMobileStart: currentData.ActionProxyUserRealName.value,
          branchMode: '',
          isDelayTr: '',
          deptName: '',
          deptField: '',
          canSelUserWhenReturned: '',
          flagSaveArchive: '0',
          formView: '0',
          isMsg:
            currentData?.ActionIsMsg?.value == '1' || currentData?.ActionIsMsg?.value == ''
              ? true
              : false,
          isModuleFilter: '',
          isBtnSaveShow: true,
          btnAgreeName: '',
          btnRefuseName: '',
          isShowNextUsers: true,
          redirectUrl: '',
          internalName: id,
          subFlowTypeCode: '',
          trMapField: '',
          p2s: '',
          s2P: '',

          OfficeColorIndex: currentData?.ActionColorIndex?.value,
          direction: currentData?.ActionProxyJobCode?.value,
          fieldWrite: currentData?.ActionFieldWrite?.value.replaceAll('comma', ','),
          nodeMode: currentData?.ActionDeptMode?.value,
          strategy: currentData?.ActionStrategy?.value,
          nodeScript: '',
          flagDelFlow: currentData.inDegree == 0 ? true : false,
          watermarkText: currentData?.ActionWatermarkText?.value,
        };
        if (currentFlowRecord.value['nodeMode'] == '0') {
          currentFlowRecord.value['spanMode'] = '角色';
        } else if (currentFlowRecord.value['nodeMode'] == '4') {
          currentFlowRecord.value['spanMode'] = '岗位';
        } else {
          currentFlowRecord.value['spanMode'] = '用户';
        }
        if (currentFlowRecord.value['userRealName'] === '$nodeScript') {
          // o("nodeScriptTr").style.display = "";
        }

        const flag = currentData?.ActionFlag?.value;
        if (flag) {
          if (flag.length >= 1) {
            if (flag.substr(0, 1) != '1') currentFlowRecord.value['flagModify'] = false;
            else currentFlowRecord.value['flagModify'] = true;
          } else currentFlowRecord.value['flagModify'] = false;
          if (flag.length >= 2) {
            if (flag.substr(1, 1) == '1') currentFlowRecord.value['flagSel'] = true;
            else currentFlowRecord.value['flagSel'] = false;
          } else currentFlowRecord.value['flagSel'] = false;
          //flag.length长度为2时，是给新创建的节点设置属性

          if (flag.length >= 3) {
            if (flag.substr(2, 1) == '1') {
              currentFlowRecord.value['flagDiscardFlow'] = true;
            } else currentFlowRecord.value['flagDiscardFlow'] = false;
          } else currentFlowRecord.value['flagDiscardFlow'] = false;

          if (flag.length >= 4) {
            if (flag.substr(3, 1) == '1') {
              currentFlowRecord.value['flagDelFlow'] = true;
            } else
              currentFlowRecord.value['flagDelFlow'] = currentData.inDegree == 0 ? true : false;
          } else currentFlowRecord.value['flagDelFlow'] = currentData.inDegree == 0 ? true : false;

          if (flag.length >= 5) {
            currentFlowRecord.value['flagSaveArchive'] = flag.substr(4, 1) || '0';
          } else {
            currentFlowRecord.value['flagSaveArchive'] = '0';
          }

          if (flag.length >= 6) {
            if (flag.substr(5, 1) == '1') {
              currentFlowRecord.value['flagDelAttach'] = true;
            } else currentFlowRecord.value['flagDelAttach'] = false;
          } else currentFlowRecord.value['flagDelAttach'] = false;

          if (flag.length >= 7) {
            if (flag.substr(6, 1) == '1') {
              currentFlowRecord.value['flagXorRadiate'] = true;
            } else {
              currentFlowRecord.value['flagXorRadiate'] = false;
            }
          } else {
            currentFlowRecord.value['flagXorRadiate'] = false;
          }

          if (flag.length >= 8) {
            if (flag.substr(7, 1) == '1') {
              currentFlowRecord.value['flagXorAggregate'] = true;
            } else {
              currentFlowRecord.value['flagXorAggregate'] = false;
            }
          } else {
            currentFlowRecord.value['flagXorAggregate'] = false;
          }

          if (flag.length >= 9) {
            if (flag.substr(8, 1) == '1') {
              currentFlowRecord.value['flagFinishFlow'] = true;
            } else {
              currentFlowRecord.value['flagFinishFlow'] = false;
            }
          } else {
            currentFlowRecord.value['flagFinishFlow'] = false;
          }

          if (flag.length >= 10) {
            if (flag.substr(9, 1) == '1') {
              currentFlowRecord.value['flagEditAttach'] = true;
            } else {
              currentFlowRecord.value['flagEditAttach'] = false;
            }
          } else {
            currentFlowRecord.value['flagEditAttach'] = false;
          }

          if (flag.length >= 11) {
            if (flag.substr(10, 1) == '1') {
              currentFlowRecord.value['flagReceiveRevise'] = true;
            } else {
              currentFlowRecord.value['flagReceiveRevise'] = false;
            }
          } else {
            currentFlowRecord.value['flagReceiveRevise'] = false;
          }

          if (flag.length >= 12) {
            if (flag.substr(11, 1) == '1') {
              currentFlowRecord.value['flagAgreeAndFinish'] = true;
            } else {
              currentFlowRecord.value['flagAgreeAndFinish'] = false;
            }
          } else {
            currentFlowRecord.value['flagAgreeAndFinish'] = false;
          }

          if (flag.length >= 13) {
            if (flag.substr(12, 1) == '1') {
              currentFlowRecord.value['flagXorFinish'] = true;
            } else {
              currentFlowRecord.value['flagXorFinish'] = false;
            }
          } else {
            currentFlowRecord.value['flagXorFinish'] = false;
          }

          if (flag.length >= 14) {
            if (flag.substr(13, 1) == '1') {
              currentFlowRecord.value['flagXorReturn'] = true;
            } else {
              currentFlowRecord.value['flagXorReturn'] = false;
            }
          } else {
            currentFlowRecord.value['flagXorReturn'] = false;
          }
          if (flag.length >= 15) {
            if (flag.substr(14, 1) == '1') {
              currentFlowRecord.value['flagSeal'] = true;
            } else {
              currentFlowRecord.value['flagSeal'] = false;
            }
          } else {
            currentFlowRecord.value['flagSeal'] = false;
          }

          if (flag.length >= 16) {
            if (flag.substr(15, 1) == '1') {
              currentFlowRecord.value['flagTransfer'] = true;
            } else {
              currentFlowRecord.value['flagTransfer'] = false;
            }
          } else {
            currentFlowRecord.value['flagTransfer'] = false;
          }

          if (flag.length >= 17) {
            if (flag.substr(16, 1) == '1') {
              currentFlowRecord.value['flagReaded'] = true;
            } else {
              currentFlowRecord.value['flagReaded'] = false;
            }
          } else {
            currentFlowRecord.value['flagReaded'] = false;
          }

          if (flag.length >= 18) {
            if (flag.substr(17, 1) == '1') {
              currentFlowRecord.value['flagCircleRead'] = true;
            } else {
              currentFlowRecord.value['flagCircleRead'] = false;
            }
          } else {
            currentFlowRecord.value['flagCircleRead'] = false;
          }

          if (flag.length >= 19) {
            if (flag.substr(18, 1) == '1') {
              currentFlowRecord.value['flagForceRecall'] = true;
            } else {
              currentFlowRecord.value['flagForceRecall'] = false;
            }
          } else {
            currentFlowRecord.value['flagForceRecall'] = false;
          }

          if (flag.length >= 20) {
            if (flag.substr(19, 1) == '1') {
              currentFlowRecord.value['flagAppendUser'] = true;
            } else {
              currentFlowRecord.value['flagAppendUser'] = false;
            }
          } else {
            currentFlowRecord.value['flagAppendUser'] = false;
          }

          if (flag.length >= 21) {
            if (flag.substr(20, 1) == '1') {
              currentFlowRecord.value['flagWatermark'] = true;
            } else {
              currentFlowRecord.value['flagWatermark'] = false;
            }
          } else {
            currentFlowRecord.value['flagWatermark'] = false;
          }
        }

        // 从旧版升级过来的item2中可能含有comma
        //确实存在，set值以后再次点击节点会出现
        let item2 = currentData?.ActionItem2?.value;
        if (item2) {
          item2 = item2.replaceAll('comma', ',');
        }
        // console.log('item2=' + item2);
        // 解析item2，格式{ relateToAction , ignoreType , kind , fieldHide , isDelayed , timeDelayedValue , timeDelayedUnit , canPrivUserModifyDelayDate, formView, relateDeptManager };
        if (item2 && item2.length >= 2) {
          const items = item2.substring(1, item2.length - 1);
          const itemAry = items.split(',');
          if (itemAry.length >= 1) {
            if (itemAry[0].length > 0) {
              currentFlowRecord.value['relateToAction'] = itemAry[0] ? itemAry[0] : 'default';
            }
            if (itemAry.length >= 2) {
              currentFlowRecord.value['ignoreType'] = itemAry[1];
            }
            if (itemAry.length >= 3) {
              currentFlowRecord.value['kind'] = itemAry[2] || '0';
              switchKind(itemAry[2]);
            } else {
              switchKind('0');
            }
            if (itemAry.length >= 4) {
              currentFlowRecord.value['fieldHide'] = itemAry[3].replaceAll('\\|', ',');
            }

            if (itemAry.length >= 5) {
              if (itemAry[4] == '1') currentFlowRecord.value['isDelayed'] = true;
            }
            if (itemAry.length >= 6) {
              currentFlowRecord.value['timeDelayedValue'] = itemAry[5];
            }
            if (itemAry.length >= 7) {
              currentFlowRecord.value['timeDelayedUnit'] = itemAry[6];
            }
            if (itemAry.length >= 8) {
              if (itemAry[7] == 1) currentFlowRecord.value['canPrivUserModifyDelayDate'] = true;
            }
            if (itemAry.length >= 9) {
              currentFlowRecord.value['formView'] = itemAry[8] || '0';
            }
            if (itemAry.length >= 10) {
              if (itemAry[9] == 1) {
                currentFlowRecord.value['relateDeptManager'] = true;
              }
            }
          } else {
            switchKind('0');
          }
        } else {
          switchKind('0');
        }

        currentFlowRecord.value['msgProps'] = useFlow.flowEdit?.msgProps;

        if (
          currentFlowRecord.value['msgProps'] &&
          currentFlowRecord.value['msgProps'].indexOf('<actions>') == 0 &&
          currentFlowRecord.value['msgProps'].indexOf('internalName=' + `"${id}"`) != -1
        ) {
          currentFlowRecord.value['isImgComb'] = true;
        } else {
          currentFlowRecord.value['isImgComb'] = false;
        }

        let props = useFlow.flowEdit?.props; //window.parent.getProps();
        let xml = $.parseXML(props);
        console.log({ props, xml });
        let $xml = $(xml);
        console.log('$xml', $xml);
        try {
          $xml
            .find('actions')
            .children()
            .each(function (i) {
              if ($(this).attr('internalName') == id) {
                console.log("$(this).find('property').text()", $(this).find('property').text());

                let prop = $(this).find('property').text()
                  ? $.parseJSON($(this).find('property').text())
                  : '';
                console.log('prop', prop);
                if (prop) {
                  currentFlowRecord.value['subFlowTypeCode'] = prop.subFlowTypeCode;

                  // getSubFields();

                  currentFlowRecord.value['parentToSubMap'] = prop.parentToSubMap;
                  // let parentToSubMap = prop.parentToSubMap;
                  // $.each(parentToSubMap, function (i, it) {
                  //     makeP2S(tmpId, this.parentField, this.parentTitle, this.subField, this.subTitle);
                  //     tmpId++;
                  // });

                  currentFlowRecord.value['subToParentMap'] = prop.subToParentMap;
                  // let subToParentMap = prop.subToParentMap;
                  // $.each(subToParentMap, function (i, it) {
                  //     makeS2P(tmpId, this.parentField, this.parentTitle, this.subField, this.subTitle);
                  //     tmpId++;
                  // });
                }

                let redirectUrl = $(this).find('redirectUrl').text();
                if (redirectUrl) {
                  currentFlowRecord.value['redirectUrl'] = redirectUrl;
                }

                let nodeScript = $(this).find('nodeScript').text();
                if (nodeScript) {
                  currentFlowRecord.value['nodeScript'] = nodeScript;
                }
                console.log('nodeScript', nodeScript);

                let isModuleFilter = $(this).find('isModuleFilter').text();
                if (isModuleFilter == '1') {
                  currentFlowRecord.value['isModuleFilter'] = true;
                }

                let branchMode = $(this).find('branchMode').text();
                if (branchMode) {
                  currentFlowRecord.value['branchMode'] = branchMode;
                }

                let btnAgreeName = $(this).find('btnAgreeName').text();
                if (btnAgreeName) {
                  currentFlowRecord.value['btnAgreeName'] = btnAgreeName;
                }
                let isBtnSaveShow = $(this).find('isBtnSaveShow').text();
                if (isBtnSaveShow) {
                  currentFlowRecord.value['isBtnSaveShow'] = isBtnSaveShow == '1' ? true : false;
                } else {
                  currentFlowRecord.value['isBtnSaveShow'] = true;
                }

                let btnRefuseName = $(this).find('btnRefuseName').text();
                if (btnRefuseName) {
                  currentFlowRecord.value['btnRefuseName'] = btnRefuseName;
                }

                let isShowNextUsers = $(this).find('isShowNextUsers').text();
                console.log('handleCurrentItem isShowNextUsers', isShowNextUsers);
                // 判断是否为空，是为了向下兼容
                if (isShowNextUsers == '' || isShowNextUsers == '1') {
                  currentFlowRecord.value['isShowNextUsers'] = true;
                } else {
                  currentFlowRecord.value['isShowNextUsers'] = false;
                }

                let deptField = $(this).find('deptField').text();
                if (deptField) {
                  // $('#deptField').val(deptField);
                  currentFlowRecord.value['deptField'] = deptField;
                }

                // 被退回再提交时能否重新选择用户
                let canSelUserWhenReturned = $(this).find('canSelUserWhenReturned').text();
                if (canSelUserWhenReturned) {
                  // $('#canSelUserWhenReturned').attr('checked', true);
                  currentFlowRecord.value['canSelUserWhenReturned'] = true;
                }

                return false;
              }
            });
        } catch (err) {
          console.log('props', err);
        }
        console.log('currentFlowRecord.value', currentFlowRecord.value);
        useFlow.setCurrentFlowData(currentFlowRecord.value);
        emit('select', 'rect');
      };

      function xmlEncode(c) {
        return c
          .replaceAll('<', '&lt;')
          .replaceAll('>', '&gt;')
          .replaceAll('&', '&amp;')
          .replaceAll('"', '&quot;');
      }

      function PlayDesigner() {
        $flow.resetAllRectStatus();
        doPlayDesigner();
      }

      let playCount = 0;
      function doPlayDesigner() {
        let ary = [];
        let kk = 0;
        flowData.value.aryMyAction.forEach((json) => {
          let receiveTime = json.receiveTime;
          ary[kk] = [receiveTime, json.internalName, json.actionStatus]; // 到达
          kk++;
          let checkTime = json.checkTime;
          ary[kk] = [checkTime, json.internalName, json.checkStatus]; // 处理
          kk++;
        });
        // [# th:each="json,stat : ${aryMyAction}"]
        //     let receiveTime = "[(${json.receiveTime})]";
        //     ary[kk] = [receiveTime, "[(${json.internalName})]", "[(${json.actionStatus})]]"]; // 到达
        //     kk++;
        //     let checkTime = "[(${json.checkTime})]";
        //     ary[kk] = [checkTime, "[(${json.internalName})]", "[(${json.checkStatus})]"]; // 处理
        //     kk++;
        // [/]

        if (playCount == 0) {
          // 对ary中的元素按照时间排序
          ary.sort(function (a, b) {
            return parseInt(a[0]) - parseInt(b[0]);
          });
        }

        let rectId = ary[playCount][1];
        let status = ary[playCount][2];
        if (status == flowData.value.STATE_DOING) {
          status = 'active';
        } else if (status == flowData.value.STATE_FINISHED) {
          status = 'finish';
        } else if (status == flowData.value.STATE_RETURN) {
          status = 'return';
        } else if (status == flowData.value.STATE_IGNORED) {
          status = 'ignore';
        } else if (status == flowData.value.STATE_DISCARDED) {
          status = 'discard';
        }

        $flow.setRectStatus(rectId, status);

        playCount++;

        if (playCount == ary.length) {
          $.toaster({ priority: 'info', message: '[(#{endPlayback})]' });
          playCount = 0;
          return;
        }

        // timeoutid = window.setTimeout('doPlayDesigner()', '1000');
        timeoutid = setTimeout(() => {
          doPlayDesigner();
        }, 1000);
      }

      function handleSuccess() {}
      onMounted(() => {
        window.ajaxGet = ajaxGet;
        window.ajaxPost = ajaxPost;
        fetch();
      });

      //重绘流程图
      const handleResize = () => {
        $flow.resize();
      };
      function getLink(linkId) {
        var myflow = $.myflow;
        return myflow.getPaths()[linkId];
      }
      //点击线
      function OpenLinkPropertyWin(linkId) {
        const curLink = getLink(linkId);
        useFlow.setCurLink(curLink);
        console.log('curLink1', curLink);
        console.log('curLink3', useFlow.curLink);
        // var t = GetSelectedLinkProperty('title');
        // var conditionType = GetSelectedLinkProperty('conditionType');
        // t = encodeURI(t);

        // $('#tabs').tabs('option', 'active', 1);
        // ----->
        // title在flow_designer_link_prop.jsp中传过去时用不到，并且可能因为title中含有脚本，导致url太长，而使得flow_designer_link_prop.jsp页面显示为空
        // o('actionPropIframe').src = "flow_designer_link_prop.jsp?linkProp="+$('#linkProp').val()+"&flowTypeCode=<%=flowTypeCode%>&conditionType=" + conditionType; // + "&title=" + t;

        // ----->
        // var url = 'flow_designer_link_prop.jsp';
        // var tempForm = document.createElement('form');
        // tempForm.id = 'tempForm1';
        // tempForm.method = 'post';
        // tempForm.action = url;

        // var hideInput = document.createElement('input');
        // hideInput.type = 'hidden';
        // hideInput.name = 'linkProp';
        // hideInput.value = $('#linkProp').html();
        // tempForm.appendChild(hideInput);

        // hideInput = document.createElement('input');
        // hideInput.type = 'hidden';
        // hideInput.name = 'flowTypeCode';
        // hideInput.value = '<%=flowTypeCode%>';
        // tempForm.appendChild(hideInput);

        // hideInput = document.createElement('input');
        // hideInput.type = 'hidden';
        // hideInput.name = 'conditionType';
        // hideInput.value = conditionType;
        // tempForm.appendChild(hideInput);

        // hideInput = document.createElement('input');
        // hideInput.type = 'hidden';
        // hideInput.name = 'title';
        // hideInput.value = t;
        // tempForm.appendChild(hideInput);

        // document.body.appendChild(tempForm);
        // tempForm.target = 'actionPropIframe';
        // tempForm.submit();
        // document.body.removeChild(tempForm);

        // openWin("flow_predefine_link_modify.jsp?flowTypeCode=<%=flowTypeCode%>&conditionType=" + conditionType + "&title=" + t, 620, 320);
      }

      function OpenLinkPropertyNormalWin(linkId) {
        const curLink = getLink(linkId);
        useFlow.setCurLink = curLink;

        console.log('curLink2', curLink);
        // var t = GetSelectedLinkProperty('title');
        // t = encodeURI(t);

        // $('#tabs').tabs('option', 'active', 1);
        // o('actionPropIframe').src = 'flow_designer_link_normal_prop_myflow.jsp?title=' + t;
      }
      return {
        handleSuccess,
        PlayDesigner,
        fetch,
      };
    },
  });
</script>
<style lang="less" scoped>
  @import '/@/assets/css/myflow.css';
  .bg-white {
    position: relative;
    .isPlay {
      position: absolute;
      top: 0;
      left: 50%;
    }
    .node {
      display: flex;
    }
  }
</style>
